import config from '@/common/js/env.config.js'
import useAppStore from '@/store/app.js'

const {
    BASE_API
} = config

const DEFAULT_PARAMS = {
    baseURL: BASE_API, // 自定义 baseURL
    needLogin: false, // 是否需要登录
    showLoading: false, // 显示loading
    showError: true, // 显示错误信息
}

const request = (url, data = {}, params = {}, method = 'GET') => {
	const appStore = useAppStore()
    const _params = Object.assign({}, DEFAULT_PARAMS, params);
    return new Promise((resolve, reject) => {
        if (_params.showLoading) {
            uni.showLoading({
                title: '加载中...',
                mask: true
            })
        }
        uni.request({
            url: _params.baseURL + url,
            data,
            method,
            header: {
                'X-Requested-With': 'XMLHttpRequest',
                "Accept": "application/json",
                "Content-Type": 'application/json',
                'Token': appStore.token,
            },
            dataType: 'json',
            success: (res) => {
                const responseData = interceptor(res.data);
                if (responseData.code === 0) {
                    resolve(responseData);
                } else {
                    if (_params.showError) {
                        throwErr(responseData);
                    }
                    reject(res);
                }
            },
            fail: function (err) {
                reject(err)
            },
            complete: () => {
                if (_params.showLoading) {
                    uni.hideLoading()
                }
            }
        })
    });
};

// GET 请求封装
const get = (url, data = {}, params = {}) => {
    return request(url, data, params, 'GET');
};

// POST 请求封装
const post = (url, data = {}, params = {}) => {
    return request(url, data, params, 'POST');
};
// PUT 请求封装
const put = (url, data = {}, params = {}) => {
    return request(url, data, params, 'PUT');
};

// DELETE 请求封装
const del = (url, data = {}, params = {}) => {
    return request(url, data, params, 'DELETE');
};

// 请求拦截
function interceptor(response) {
	const appStore = useAppStore()
    if (response.code === 200401) {
		// uni.$u.toast('未登录或登录过期，请重新登录')
        console.log('未登录或登录过期，即将重新登录')
		setTimeout(()=> {
			appStore.logout()
		}, 1000)
        // uni.showToast({
        //     title: response.msg,
        //     icon: 'none',
        //     duration: 2000,
        //     complete: () => {
        //         uni.reLaunch({
        //             url: '/pages/bindex/bindex',
        //         });
        //     },
        // });
        return false;
    }
    return response;
}

// 处理错误
function throwErr(res) {
    if (res.code == 500) {
        uni.showToast({
            title: res.msg,
        })
    }
}

export {
    get,
    post,
    put,
    del
}